# Create your views here.
from django.db.models import Q
from rest_framework import status
from rest_framework.generics import ListAPIView, GenericAPIView, RetrieveAPIView, CreateAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated

from rest_framework.response import Response

from complains.utils.pagination import StandardResultsSetPagination
from quesanw.models import QuestionModel, AnswerModel, TagModel, QuestionTagModel, QuestionFocusModel, \
    UsefulChangeModel, \
    AnswerUsefulModel, UserFocusTagModel
from quesanw.serializers import QuestionSerializer, AnswerSerializer, TagSerializer, TagQuestionSerializer, \
    UserSerializer, QuestionFocusSerializer, UsefulChangeSerializer, AnswerUsefulSerializer, AnswerSerializer111, \
    QuestionSerializer1, QuestionTagSerializer, AnswerListSerializer, QuestionSubmitSerializer, UserFocusTagSerializer

from quesanw.utils import MyPagination

"""
 问答详情页接口需求：
    1.时间：问题发布成功后，仅显示提问时间，提问规则为多久前提问，当作者对问题重新编辑后，则在发布时间后增加更新时间
      规则同上一个时间
    2.问题正文的左上角的箭头通过点击可对问题权重进行投票，向上为 + 1，向下为 - 1，每个用户仅可点击一次。
    3.评论：点击后显示输入框
    4. 编辑：仅在作者页面显示，用户查看不显示
    5. 举报：点击举报可投诉该问题
"""


class QuestionDetailView(RetrieveAPIView):
    queryset = QuestionModel.objects.all()
    serializer_class = QuestionSerializer

    # def perform_authentication(self, request):
    #     """
    #     重写父类的用户验证方法，不在进入视图前就检查JWT
    #     """
    #     pass

    def retrieve(self, request, *args, **kwargs):
        pk = kwargs.get("pk")
        if not QuestionModel.objects.filter(id=pk):
            response = Response({'errmsg': '页面不存在'}, status=status.HTTP_404_NOT_FOUND)
            return response

        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = serializer.data
        user_id = request.user.id
        print("hahaha%s" % request.user.id)
        is_click = None
        if not user_id:
            data["is_click"] = True
        else:
            try:
                _query = QuestionFocusModel.objects.filter(question_id=pk).filter(user_id=user_id).first()

            except:

                response = Response({'errmsg': '数据库查询失败'}, status=status.HTTP_404_NOT_FOUND)
                return response

            if not _query:
                is_click = False
            else:
                is_click = _query.is_click
        data["is_click"] = is_click

        return Response(data)


class FocusView(CreateAPIView, UpdateAPIView):
    queryset = QuestionFocusModel.objects.all()
    serializer_class = QuestionFocusSerializer

    def get_object(self):
        print("hahh%s" % self.request.data)
        id = self.request.data.get("question")
        user = self.request.data.get("user")

        obj = QuestionFocusModel.objects.filter(question_id=id).filter(user_id=user).first()
        return obj




class UsefulChangeView(CreateAPIView, UpdateAPIView):
    """
    1.先判断用户是否在线，获取用户的指令
    2.如果为add，判断状态是否能够加，反之，判断能否减
    3.操作成功后，更改状态
    """
    queryset = UsefulChangeModel.objects.all()
    serializer_class = UsefulChangeSerializer

    def get_object(self):
        self.user_id = self.request.data.get("user")
        self.question_id = self.request.data.get("question")

        if not self.user_id:
            response = Response({'errmsg': '用户未登陆'}, status=status.HTTP_401_UNAUTHORIZED)
            return response
        try:
            obj = UsefulChangeModel.objects.filter(user_id=self.user_id).filter(question_id=self.question_id).first()
        except:
            response = Response({'errmsg': '数据库查询失败'}, status=status.HTTP_404_NOT_FOUND)
            return response
        return obj

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        action = self.request.data.get("action")
        # 登陆了判断action和instance
        if action == "add" and instance is None:
            data = {
                "user": self.user_id,
                "question": self.question_id,
                "is_useful": 3
            }
            ques_obj = QuestionModel.objects.filter(pk=self.question_id).first()
            ques_obj.count += 1
            ques_obj.save()
        elif action == "reduce" and instance is None:
            data = {
                "user": self.user_id,
                "question": self.question_id,
                "is_useful": 1
            }
            ques_obj = QuestionModel.objects.filter(pk=self.question_id).first()
            ques_obj.count -= 1
            ques_obj.save()
        elif action == "reduce" and instance:
            obj = UsefulChangeModel.objects.filter(user_id=self.user_id).filter(question_id=self.question_id).first()
            is_useful = obj.is_useful
            if is_useful == 1:
                raise Exception("已经踩过了")
            is_useful = 1
            ques_obj = QuestionModel.objects.filter(pk=self.question_id).first()
            ques_obj.count -= 1
            ques_obj.save()
            data = {
                "user": self.user_id,
                "question": self.question_id,
                "is_useful": is_useful
            }
        elif action == "add" and instance:
            obj = UsefulChangeModel.objects.filter(user_id=self.user_id).filter(question_id=self.question_id).first()
            is_useful = obj.is_useful
            if is_useful == 3:
                raise Exception("已经赞过了")
            is_useful = 3
            ques_obj = QuestionModel.objects.filter(pk=self.question_id).first()
            # print(ques_obj)
            # print("count%s"%ques_obj.count)
            ques_obj.count += 1
            ques_obj.save()
            data = {
                "user": self.user_id,
                "question": self.question_id,
                "is_useful": is_useful
            }
        serializer = self.get_serializer(instance, data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}
        return Response(data)


class AnswerUsefulView(CreateAPIView, UpdateAPIView):
    """
    1.先判断用户是否在线，获取用户的指令
    2.如果为add，判断状态是否能够加，反之，判断能否减
    3.操作成功后，更改状态
    """
    queryset = AnswerUsefulModel.objects.all()
    serializer_class = AnswerUsefulSerializer

    def get_object(self):
        self.user_id = self.request.data.get("user")
        self.answer_id = self.request.data.get("answer")

        if not self.user_id:
            response = Response({'errmsg': '用户未登陆'}, status=status.HTTP_401_UNAUTHORIZED)
            return response
        try:
            obj = AnswerUsefulModel.objects.filter(user_id=self.user_id).filter(
                answer_id=self.answer_id).first()
        except:
            response = Response({'errmsg': '数据库查询失败'}, status=status.HTTP_404_NOT_FOUND)
            return response
        return obj

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        action = self.request.data.get("action")
        # 登陆了判断action和instance
        if action == "add" and instance is None:
            data = {
                "user": self.user_id,
                "answer": self.answer_id,
                "is_useful": 3
            }
            ques_obj = AnswerModel.objects.filter(pk=self.answer_id).first()
            ques_obj.count += 1
            ques_obj.save()
        elif action == "reduce" and instance is None:
            data = {
                "user": self.user_id,
                "answer": self.answer_id,
                "is_useful": 1
            }
            ques_obj = AnswerModel.objects.filter(pk=self.answer_id).first()
            ques_obj.count -= 1
            ques_obj.save()
        elif action == "reduce" and instance:
            obj = AnswerUsefulModel.objects.filter(user_id=self.user_id).filter(
                answer_id=self.answer_id).first()
            is_useful = obj.is_useful
            if is_useful == 1:
                raise Exception("已经踩过了")
            is_useful = 1
            ques_obj = AnswerModel.objects.filter(pk=self.answer_id).first()
            ques_obj.count -= 1
            ques_obj.save()
            data = {
                "user": self.user_id,
                "answer": self.answer_id,
                "is_useful": is_useful
            }
        elif action == "add" and instance:
            obj = AnswerUsefulModel.objects.filter(user_id=self.user_id).filter(
                answer_id=self.answer_id).first()
            is_useful = obj.is_useful
            if is_useful == 3:
                raise Exception("已经赞过了")
            is_useful = 3
            ques_obj = AnswerModel.objects.filter(pk=self.answer_id).first()
            # print(ques_obj)
            # print("count%s"%ques_obj.count)
            ques_obj.count += 1
            ques_obj.save()
            data = {
                "user": self.user_id,
                "answer": self.answer_id,
                "is_useful": is_useful
            }
        serializer = self.get_serializer(instance, data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}
        return Response(data)


class AnswerQuestionSerializer(CreateAPIView):
    queryset = AnswerModel.objects.all()
    serializer_class = AnswerSerializer111


class QuestionChangeSeralizer(UpdateAPIView):
    queryset = QuestionModel.objects.all()
    serializer_class = QuestionSerializer1

    def update(self, request, *args, **kwargs):
        print("hahahahah%s" % request.user.id)
        print(request.data)

        partial = kwargs.pop('partial', False)
        instance = self.get_object()

        title = instance.title
        author = instance.author.id
        data = {
            "detail": request.data.get("detail"),
            "title": title,
            "author": author,
        }
        serializer = self.get_serializer(instance, data=data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)


class QuestionListView(ListAPIView):
    pagination_class = StandardResultsSetPagination
    serializer_class = QuestionSerializer

    def get_queryset(self):
        tag = self.request.query_params.get('catalog', None)
        show = self.request.query_params.get('show', None)

        if tag == 'index':
            if not show or show == 'update':
                queryset = QuestionModel.objects.filter(comment_num__gt=0).order_by('-update_time')
            elif show == 'hot':
                queryset = QuestionModel.objects.all().order_by('-comment_num')
            else:
                queryset = QuestionModel.objects.filter(comment_num=0).order_by('-update_time')
        else:
            tag = int(tag)
            question_tag = QuestionTagModel.objects.filter(tag_id=tag)
            question_tag_list = QuestionTagSerializer(question_tag, many=True).data
            question_id = []
            for i in question_tag_list:
                question_id.append(i['question'])
            if not show or show == 'update':
                queryset = QuestionModel.objects.filter(id__in=question_id, comment_num__gt=0).order_by('-update_time')
            elif show == 'hot':
                queryset = QuestionModel.objects.filter(id__in=question_id).order_by('-comment_num')
            elif show == 'count':
                queryset = QuestionModel.objects.filter(id__in=question_id).order_by('-count')
            else:
                queryset = QuestionModel.objects.filter(id__in=question_id, comment_num=0).order_by('-update_time')

        return queryset

    def get(self, request):
        response = super().get(request)

        # show = request.query_params.get('show',None)
        # tag = request.query_params.get('catalog', None)
        #
        # if not tag and not show:
        #     return response
        # else:
        # queryset = self.get_queryset()
        # question_list = QuestionSerializer(queryset, many=True).data
        for i, q in enumerate(response.data["results"]):
            q_id = q['id']
            answer = AnswerModel.objects.filter(question_id=q_id)
            if answer:
                answer = answer.order_by('-create_time')[0]
                answer_data = AnswerListSerializer(answer).data
                response.data["results"][i]['answer'] = answer_data
        return response


class TagListView(ListAPIView):
    serializer_class = TagSerializer
    queryset = TagModel.objects.all().order_by("-quote_total")
    pagination_class = StandardResultsSetPagination

    def perform_authentication(self, request):
        """将执行具体请求方法前的身份认证关掉，由视图自己来进行身份认证"""
        pass

    def get(self, request):
        response = super().get(request)
        try:
            user = request.user  # 匿名用户 AnonymoseUser
        except Exception:
            user = None
        for i, tag in enumerate(response.data["results"]):
            if user:
                try:
                    tagfocus = UserFocusTagModel.objects.get(Q(user_id=user.id) & Q(tag_id=tag['id']) & Q(is_focus=1))
                except:
                    tagfocus = None
                if tagfocus:
                    response.data["results"][i]['is_focus'] = tagfocus.is_focus
                else:
                    response.data["results"][i]['is_focus'] = False
            else:
                response.data["results"][i]['is_focus'] = False
        return response


class TagDetailView(RetrieveAPIView):
    serializer_class = TagSerializer
    queryset = TagModel.objects.all()


class QuestionSubmitView(CreateAPIView):
    serializer_class = QuestionSubmitSerializer
    # permission_classes = [IsAuthenticated]


class QuestionSearchView(ListAPIView):
    pagination_class = StandardResultsSetPagination
    serializer_class = QuestionSerializer

    def get_queryset(self):
        search_string = self.request.query_params['keyword']
        queryset = QuestionModel.objects.filter(title__contains=search_string)
        return queryset


class TagSearchView(ListAPIView):
    serializer_class = TagSerializer
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):
        search_string = self.request.query_params['keyword']
        queryset = TagModel.objects.filter(name__contains=search_string)
        return queryset


class UserFoucsDetailTagView(RetrieveAPIView, UpdateAPIView):
    serializer_class = UserFocusTagSerializer

    def get_object(self):
        tag_id = self.kwargs['tag']
        user_id = self.kwargs['user']
        try:
            usertag = UserFocusTagModel.objects.get(Q(user_id=user_id) & Q(tag_id=tag_id))
        except:
            usertag = None
        else:
            return usertag
